package com.example.bigdata.scala.Jackson解析

import java.io.{File, StringReader}

import com.fasterxml.jackson.databind
import com.fasterxml.jackson.databind.{DeserializationFeature, ObjectMapper}
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import org.codehaus.jackson.JsonNode

import scala.io.Source

object JacksonDemo {
    def main(args: Array[String]): Unit = {
//        json2Object
//        json2LiuObject
        file2Map
//        json2File
    }

    def json2Object(): Unit ={
        val mapper = new ObjectMapper() //com.fasterxml.jackson.core
        // 选择Scala 模型
        mapper.registerModule(DefaultScalaModule)
        val peopleJson = "{\"name\":\"小明\",\"age\":8,\"sex\":\"男\"}"
        val people: People = mapper.readValue(peopleJson,classOf[People])
        printf(s"姓名 = ${people.name} , 年龄 = ${people.age} , 性别 = ${people.sex}")
    }
    def json2LiuObject(): Unit ={
        val mapper = new ObjectMapper() //com.fasterxml.jackson.core
        // 选择Scala 模型
        mapper.registerModule(DefaultScalaModule)
        val peopleJson = "{\"name\":\"小明\",\"age\":8,\"sex\":\"男\"}"
        val reader: StringReader = new StringReader(peopleJson)
        val people: People = mapper.readValue(reader,classOf[People])
        printf(s"姓名 = ${people.name} , 年龄 = ${people.age} , 性别 = ${people.sex}")
    }

    def file2Map(): Unit ={
        val jsonFile = Source.fromFile("input/json/user1.json", "UTF-8").mkString
        println(jsonFile)
        val mapper = new ObjectMapper() //com.fasterxml.jackson.core
//        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        // 选择Scala 模型
        mapper.registerModule(DefaultScalaModule)
        val value = mapper.readValue(jsonFile,classOf[Map[String,String]]).get("message").toString.toString
        println("val : " + value)
        /* for ( x <- msg) {
             println("x : " + x)
         }*/

    }

    def json2File(): Unit ={
        val mapper: ObjectMapper = new ObjectMapper()
        val peopleJson = "{\"name\":\"小明\",\"age\":8,\"sex\":\"男\"}"
        val jsonNode: databind.JsonNode = mapper.readTree(peopleJson)
        println(jsonNode.get("name"))
    }


}
